package com.sftz.modules.minapp.homepage.service;

import java.util.List;
import java.util.Map;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.common.collect.Maps;
import com.sftz.assets.entities.FansTabEntity;
import com.sftz.assets.entities.FollowingEntity;
import com.sftz.assets.entities.SUserEntity;
import com.sftz.assets.enums.AttentionEnum;
import com.sftz.assets.enums.CourseStateEnum;
import com.sftz.assets.enums.CourseTypeEnum;
import com.sftz.modules.minapp.homepage.dto.CourseDto;
import com.sftz.modules.minapp.homepage.dto.FansDto;
import com.sftz.modules.minapp.homepage.dto.FollowDto;
import com.sftz.modules.minapp.homepage.dto.UserDataDto;
import com.sftz.modules.minapp.homepage.form.HomePageForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;
import com.uxuexi.core.web.chain.support.JsonResult;

/**
 *
 * @author   王宏伟
 * @Date	 2017年12月29日 	 
 */
@IocBean
public class HomePageViewServcie {
	private static final Log log = Logs.get();

	@Inject
	private Dao dao;
	@Inject
	private IDbDao dbDao;
	@Inject
	private SqlManager sqlManager;

	private static final int followed = 1;//已关注

	private static final int unfollowed = 2;//未关注

	public Object homepage(HomePageForm form) {
		String token = form.getToken();
		Integer userId = RedissionUserCache.getUserId(token);
		Integer othersUserId = form.getOthersUserId();
		//		othersUserId = 32;
		if (Util.isEmpty(userId)) {
			System.out.println("用户id不能为空");
			return false;
		}
		//1.获取用户信息
		Sql sql = Sqls.create(sqlManager.get("minapp_homepage_user_data"));
		sql.setParam("userId", othersUserId);
		UserDataDto userDataDto = DbSqlUtil.fetchEntity(dbDao, UserDataDto.class, sql);

		//2.获取关注状态	按钮显示（按钮显示）：1关注 （取消关注）	2取消关注（关注）
		if (!Util.isEmpty(othersUserId)) {
			FollowingEntity following = dbDao.fetch(FollowingEntity.class,
					Cnd.where("userId", "=", userId).and("followingId", "=", othersUserId));
			if (!Util.isEmpty(following)) {
				Integer status = following.getStatus();
				AttentionEnum ct = EnumUtil.get(AttentionEnum.class, status);
				switch (ct) {
				case ATTENTION:
					userDataDto.setFollowingStatus(AttentionEnum.ATTENTION.intKey());
					break;
				case CANCELATTENTION:
					userDataDto.setFollowingStatus(AttentionEnum.CANCELATTENTION.intKey());
					break;
				default:
					break;
				}
			} else {
				userDataDto.setFollowingStatus(AttentionEnum.CANCELATTENTION.intKey());
			}

		} else {
			userDataDto.setFollowingStatus(AttentionEnum.CANCELATTENTION.intKey());
		}

		//粉丝总数量
		Sql fansCountSql = Sqls.create(sqlManager.get("wx_homepage_fans_count"));
		fansCountSql.params().set("userId", othersUserId);
		fansCountSql.params().set("fansStatus", AttentionEnum.ATTENTION.intKey());
		int fansCount = DbSqlUtil.fetchInt(dbDao, fansCountSql);
		userDataDto.setFansCount(fansCount);

		//课程数量 
		Sql courseCountSql = Sqls.create(sqlManager.get("wx_homepage_course_count"));
		courseCountSql.params().set("userId", othersUserId);
		courseCountSql.params().set("courseState", CourseStateEnum.PUBLISHED.intKey());
		courseCountSql.params().set("courseType", CourseTypeEnum.USERCOURSE.intKey());
		int courseCount = DbSqlUtil.fetchInt(dbDao, courseCountSql);
		userDataDto.setCourseCount(courseCount);

		//被关注总数量
		Sql followingCountSql = Sqls.create(sqlManager.get("wx_homepage_following_count"));
		followingCountSql.params().set("userId", othersUserId);
		followingCountSql.params().set("status", AttentionEnum.ATTENTION.intKey());
		int followingCount = DbSqlUtil.fetchInt(dbDao, followingCountSql);
		userDataDto.setFollowingCount(followingCount);

		//获取用户的课程
		Sql courseSql = Sqls.create(sqlManager.get("wx_homepage_course_list"));
		courseSql.params().set("userId", othersUserId);
		courseSql.params().set("courseState", CourseStateEnum.PUBLISHED.intKey());
		courseSql.params().set("courseType", CourseTypeEnum.USERCOURSE.intKey());
		List<CourseDto> courseList = DbSqlUtil.query(dbDao, CourseDto.class, courseSql, null);

		//获取用户的粉丝
		Sql fansListSql = Sqls.create(sqlManager.get("wx_homepage_fans_list"));
		fansListSql.params().set("userId", userId);
		fansListSql.params().set("othersUserId", othersUserId);
		fansListSql.params().set("fansStatus", AttentionEnum.ATTENTION.intKey());
		List<FansDto> fansList = DbSqlUtil.query(dbDao, FansDto.class, fansListSql, null);

		//获取用户的关注
		Sql followingListSql = Sqls.create(sqlManager.get("wx_homepage_following_list"));
		followingListSql.params().set("userId", userId);
		followingListSql.params().set("othersUserId", othersUserId);
		followingListSql.params().set("status", AttentionEnum.ATTENTION.intKey());
		List<FollowDto> followingList = DbSqlUtil.query(dbDao, FollowDto.class, followingListSql, null);

		Map<String, Object> obj = Maps.newHashMap();
		obj.put("userDataDto", userDataDto);
		obj.put("courseList", courseList);
		obj.put("fansList", fansList);
		obj.put("followingList", followingList);
		return obj;
	}

	public Object getFollowing(Integer id, Integer userId, Integer othersUserId, Integer status) {
		//		userId = 32;
		follow(id, userId, status);
		//粉丝总数量
		Sql followingCountSql = Sqls.create(sqlManager.get("wx_homepage_following_count"));
		followingCountSql.params().set("userId", userId);
		followingCountSql.params().set("status", AttentionEnum.ATTENTION.intKey());
		int followingCount = DbSqlUtil.fetchInt(dbDao, followingCountSql);

		//获取用户的关注
		Sql followingListSql = Sqls.create(sqlManager.get("wx_homepage_following_list"));
		followingListSql.params().set("userId", userId);
		followingListSql.params().set("othersUserId", othersUserId);
		followingListSql.params().set("status", AttentionEnum.ATTENTION.intKey());
		List<FollowDto> followingList = DbSqlUtil.query(dbDao, FollowDto.class, followingListSql, null);

		//获取用户的粉丝
		Sql fansListSql = Sqls.create(sqlManager.get("wx_homepage_fans_list"));
		fansListSql.params().set("userId", userId);
		fansListSql.params().set("othersUserId", othersUserId);
		fansListSql.params().set("fansStatus", AttentionEnum.ATTENTION.intKey());
		List<FansDto> fansList = DbSqlUtil.query(dbDao, FansDto.class, fansListSql, null);

		Map<String, Object> obj = Maps.newHashMap();
		//返回关注状态
		if (status == AttentionEnum.ATTENTION.intKey()) {
			obj.put("status", AttentionEnum.CANCELATTENTION.intKey());
		} else {
			obj.put("status", AttentionEnum.ATTENTION.intKey());
		}
		obj.put("fansList", fansList);
		obj.put("followingList", followingList);
		obj.put("followingCount", followingCount);
		return obj;
	}

	@Aop("txDb")
	public Object follow(Integer id, Integer userId, Integer status) {
		//如果点击之前的状态为已关注，则一定存在关注数据，只需修改状态和粉丝数量
		if (!Util.isEmpty(id) && !Util.isEmpty(userId) && !Util.isEmpty(status)) {
			FollowingEntity follow = dbDao.fetch(FollowingEntity.class,
					Cnd.where("userId", "=", userId).and("followingId", "=", id));
			FansTabEntity fans = dbDao.fetch(FansTabEntity.class,
					Cnd.where("userId", "=", id).and("fansId", "=", userId));
			if (!Util.isEmpty(follow) && status == followed) {
				dbDao.update(FollowingEntity.class, Chain.make("status", unfollowed),
						Cnd.where("id", "=", follow.getId()));
				if (Util.isEmpty(fans)) {
					dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
				} else {
					dbDao.update(FansTabEntity.class, Chain.make("fansStatus", unfollowed),
							Cnd.where("id", "=", fans.getId()));
				}
			} else if (!Util.isEmpty(follow) && status == unfollowed) {
				dbDao.update(FollowingEntity.class, Chain.make("status", followed),
						Cnd.where("id", "=", follow.getId()));
				if (Util.isEmpty(fans)) {
					dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
				} else {
					dbDao.update(FansTabEntity.class, Chain.make("fansStatus", followed),
							Cnd.where("id", "=", fans.getId()));
				}
			} else {
				dbDao.insert(FollowingEntity.class, Chain.make("userId", userId).add("followingId", id));
				dbDao.insert(FansTabEntity.class, Chain.make("userId", id).add("fansId", userId));
			}
			return JsonResult.success("操作成功!");
		}
		return JsonResult.error("操作失败!");
	}

	@Aop("txDb")
	public void updateSignature(Integer userId, String sign) {
		dbDao.update(SUserEntity.class, Chain.make("sign", sign), Cnd.where("id", "=", userId));
	}

	/**
	 * 首页-获取用户信息
	 * @author	王宏伟
	 * @Date	2019年1月8日
	 */
	public SUserEntity queryUserInfo(Integer userId) {
		SUserEntity userEntity = dbDao.fetch(SUserEntity.class, Cnd.where("id", "=", userId));
		return userEntity;
	}

}
